package oakclub.model;

import oakclub.jooq.Tables;
import oakclub.jooq.tables.UsersBlock;
import org.jooq.DSLContext;

import java.sql.Timestamp;

public class BlockModel extends BaseModel
{
    public boolean isBlocked(long userId, long targetId) throws Exception
    {
        return (boolean) this.fetch(new IFetch()
        {
            @Override
            public Object fetch(DSLContext context, Object... params) throws Exception
            {
                // params
                long userId = (long) params[0];
                long targetId = (long) params[1];

                // table alias
                UsersBlock UB = Tables.USERS_BLOCK;

                // query
                return context
                    .selectOne()
                    .from(UB)
                    .where(UB.USER_ID.eq(targetId), UB.TARGET_ID.eq(userId))
                    .fetchOne(0) == 1;
            }
        }, userId, targetId);
    }

    public void blockUser(long userId, long targetId) throws Exception
    {
        this.execute(new IExecute()
        {
            @Override
            public void execute(DSLContext context, Object... params) throws Exception
            {
                // params
                long userId = (long) params[0];
                long targetId = (long) params[1];

                // table alias
                UsersBlock UB = Tables.USERS_BLOCK;

                // block
                Timestamp now = new Timestamp(System.currentTimeMillis());
                context
                    .insertInto(UB, UB.USER_ID, UB.TARGET_ID, UB.BLOCK_DATE)
                    .values(userId, targetId, now)
                    .execute();
            }
        }, userId, targetId);
    }

    public void unblockUser(long userId, long targetId) throws Exception
    {
        this.execute(new IExecute()
        {
            @Override
            public void execute(DSLContext context, Object... params) throws Exception
            {
                // params
                long userId = (long) params[0];
                long targetId = (long) params[1];

                // table alias
                UsersBlock UB = Tables.USERS_BLOCK;

                // unblock
                context
                    .delete(UB)
                    .where(UB.USER_ID.eq(targetId), UB.TARGET_ID.eq(userId))
                    .execute();
            }
        }, userId, targetId);
    }
}
